﻿using System;
using Dolany.UtilityTool;
using Missbot.Common;
using Missbot.Service;
using Missbot.Service.Dingtalk;
using MongoDB.Bson.Serialization.Attributes;
using Newtonsoft.Json;

namespace Missbot.Core.Common
{
    /// <summary>
    /// 日志服务（实现）
    /// </summary>
    public class LogSvc : ILogSvc
    {
        public void Log(string Msg, string Level)
        {
            Console.WriteLine(Msg);
            FileLogger.Log(Msg);
            var log = new LogRec {Msg = Msg, Level = Level};
            log.Insert();
        }

        public void LogError(Exception e)
        {
            Log(e.GetFullDetailMsg(), "error");
            DingtalkSvc.Send(e.GetFullDetailMsg());
        }

        public void LogError(Exception e, object param)
        {
            var detail    = new {Exception = e.GetFullDetailMsg(), param};
            var detailStr = JsonConvert.SerializeObject(detail);
            Log(detailStr, "error");
            DingtalkSvc.Send(detailStr);
        }
    }
    
    /// <summary>
    /// 日志记录
    /// </summary>
    public class LogRec : DbBaseEntity
    {
        /// <summary>
        /// 日志内容
        /// </summary>
        public string Msg { get; set; }
        
        /// <summary>
        /// 记录时间
        /// </summary>
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime LogTime { get; set; } = DateTime.Now;
        
        /// <summary>
        /// 日志等级
        /// </summary>
        public string Level { get; set; }

        /// <summary>
        /// 机器名
        /// </summary>
        public string MachineName { get; set; } = Environment.MachineName;
    }

    public static class LogRecDA
    {
        /// <summary>
        /// 插入日志
        /// </summary>
        public static void Insert(this LogRec entity)
        {
            MongoService<LogRec>.Insert(entity);
        }
    }
}